/*
 * Copyright (c) 2007 jNetX.
 * http://www.jnetx.com
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * jNetX. You shall not disclose such Confidential Information and
 * shall use it only in accordance with the terms of the license
 * agreement you entered into with jNetX.
 *
 * $Id$
 */
package com.jnetx.javax.sip.header;

import com.jnetx.javax.sip.util.ByteArrayUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.text.ParseException;

/**
 * @author <a href="mailto:dparhonin@jnetx.ru">Dmitry Parhonin</a>
 * @version $Revision$
 */
public class ContentTypeHeaderParser extends ParametrizedHeaderParserBase<ContentTypeHeaderImpl> {
    private static final Log logger = LogFactory.getLog(AllowHeaderParser.class);

    protected Log getLogger() {
        return logger;
    }

    public ContentTypeHeaderImpl createLazily(byte[] data, int start, int end) {
        return new ContentTypeHeaderImpl(data, start, end);
    }

    public ContentTypeHeaderImpl[] parse(ContentTypeHeaderImpl header, byte[] data, int start, int end) throws ParseException {
        if (header == null) header = new ContentTypeHeaderImpl();
        int startOfData = start;
        startOfData = ByteArrayUtil.firstMissing(data, ' ', startOfData, end);
        if (startOfData == -1)
            fail("Cannot parse the header!", start);
        int endOfPart = ByteArrayUtil.lastMissing(data, ' ', startOfData, end);
        if (endOfPart == -1)
            endOfPart = end;
        else
            endOfPart++;
        int startOfParameter = ByteArrayUtil.firstOccurence(data, ';', startOfData, endOfPart);
        final int endOfData = startOfParameter != -1 ? startOfParameter : endOfPart;
        final int slashPosition = ByteArrayUtil.firstOccurence(data, '/', startOfData, endOfData);
        if (slashPosition == -1)
            fail("Cannot parse media range!", startOfData);
        final String mediaType = new String(data, startOfData, slashPosition - startOfData);
        final int endOfPartTrimmed = ByteArrayUtil.lastMissing(data, ' ', startOfData, endOfPart);
        final String mediaSubType = new String(data, slashPosition + 1, endOfPartTrimmed - slashPosition);
        header.setContentType(mediaType);
        header.setContentSubType(mediaSubType);
        if (startOfParameter != -1)
            parseParameters(header, data, startOfParameter, endOfPart);
        return new ContentTypeHeaderImpl[]{header};
    }
}
/*
 * $Log$
 */